<?php
namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use think\Db;
use think\Session;

/**
 * 義工管理
 *
 * @icon fa fa-circle-o
 */
class Volunteer extends Backend
{

    /**
     * Volunteer模型对象
     * @var \app\admin\model\Volunteer
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Volunteer;
        $this->view->assign("serviceTimeTypeList", $this->model->getServiceTimeTypeList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $auth                         = Auth::instance();
        $auth_affiliated_center_id    = db('admin')->where('id', $auth->id)->value('affiliated_center_id');
        $auth_affiliated_center_arr   = db('area')->where('pid', 0)->column('id');
        $auth_affiliated_center_arr[] = 0;
        if ($auth_affiliated_center_id > 0) {
            $auth_affiliated_center_arr = explode(',', $auth_affiliated_center_id);
        }

        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where2                                      = [];
            $admin                                       = Session::get('admin');
            if ($admin['affiliated_center_id'] != 0) {
                $arr_area = explode(',', $admin['affiliated_center_id']);

                $where2['affiliated_center_id'] = ['in', $arr_area];

            }

            $list = $this->model
                ->with(['user', 'volunteerspecialty'])
                ->where(['affiliated_center_id' => ['in', $auth_affiliated_center_arr]])
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
                $region_address = db('region')->where(['id' => $row->province])->value('name');
                $city           = db('region')->where(['id' => $row->city])->value('name');
                if ($city) {
                    $region_address = $region_address . $city;
                    $district       = db('region')->where(['id' => $row->district])->value('name');
                    if ($district) {
                        $region_address = $region_address . $district;
                    }
                }
                $row->region_address = $region_address ? $region_address : '';
                $area                = db('area')->where(['id' => $row->area_one_id])->value('name');
                $two_area            = db('area')->where(['id' => $row->area_tow_id])->value('name');
                $row->area           = $area . $two_area;
                $row['id_card_hk']   = $row['id_card_front'] . $row['id_card'] . '(' . $row['id_card_after'] . ')';
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 區域義工
     */
    public function area_volunteer($ids)
    {
        $this->assignconfig("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user', 'volunteerspecialty', 'staff'])
                ->where($where)
                ->where(['volunteer.area_tow_id' => $ids])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar', 'id']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
                $row->getRelation('staff')->visible(['nickname']);
                $region_address = db('region')->where(['id' => $row->province])->value('name');
                $city           = db('region')->where(['id' => $row->city])->value('name');
                if ($city) {
                    $region_address = $region_address . $city;
                    $district       = db('region')->where(['id' => $row->district])->value('name');
                    if ($district) {
                        $region_address = $region_address . $district;
                    }
                }
                $row->region_address = $region_address ? $region_address : '';

                $area      = db('area')->where(['id' => $row->area_one_id])->value('name');
                $two_area  = db('area')->where(['id' => $row->area_tow_id])->value('name');
                $row->area = $area . $two_area;
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 查看義工列表(用到的地方：【員工賬號添加，詳情，分配義工source = staff】【培訓任務，關懷任務source = tasks】)
     */
    public function indexs($ids = null, $staff_id = 0, $source = 'staff')
    {
        $arr = explode(',', $ids);
        if (! $arr[0]) {
            $arr = [];
        }
        $arrs = [];
        foreach ($arr as $key => $value) {
            $arrs[] = (int) $value;
        }
        $this->assignconfig("arr", $arrs);
        $this->assignconfig("staff_id", $staff_id);
        $this->assignconfig("source", $source);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf                                   = ['volunteer.staff_id' => 0];
            if ($source != 'staff') {
                $where_buf = [];
            }
            if ($staff_id > 0) {
                $where_buf = ['volunteer.staff_id' => ['in', [0, $staff_id]]];
            }
            $list = $this->model
                ->with(['user', 'volunteerspecialty'])
                ->where($where)
                ->where($where_buf)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
                // $region_address = db('region')->where(['id'=>$row->province])->value('name');
                // $city = db('region')->where(['id'=>$row->city])->value('name');
                // if ( $city ) {
                //     $region_address = $region_address.$city;
                //     $district = db('region')->where(['id'=>$row->district])->value('name');
                //     if ( $district ) {
                //         $region_address = $region_address.$district;
                //     }
                // }
                // $row->region_address = $region_address?$region_address:'';
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 員工賬號管理列表，分配義工
     */
    public function indexss($ids = 0)
    {
        $arr = db('volunteer')->where(['staff_id' => $ids, 'deletetime' => null])->column('id');
        if (! $ids) {
            $arr = [];
        }
        $arrs = [];
        foreach ($arr as $key => $value) {
            $arrs[] = (int) $value;
        }
        $this->assignconfig("arr", $arrs);
        $this->assignconfig("ids", $ids);
        $this->view->assign("ids", $ids);

        if ($this->request->isPost()) {
            $ids_post = input('post.volunteer_ids');

            if ($ids_post) {
                $result = false;
                Db::startTrans();
                try {
                    db('volunteer')->where(['staff_id' => $ids])->update(['staff_id' => 0]);
                    $result = db('volunteer')->where(['id' => ['in', $ids_post]])->update(['staff_id' => $ids]);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('指派成功');
                } else {
                    $this->error(__('No rows were updated'));
                }
            }

            db('volunteer')->where(['staff_id' => $ids])->update(['staff_id' => 0]);

            $this->success('操作成功');
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf                                   = ['volunteer.staff_id' => 0];
            if ($ids > 0) {
                $where_buf = ['volunteer.staff_id' => ['in', [0, $ids]]];
            }
            $list = $this->model
                ->with(['user', 'volunteerspecialty'])
                ->where($where)
                ->where($where_buf)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
                // $region_address = db('region')->where(['id'=>$row->province])->value('name');
                // $city = db('region')->where(['id'=>$row->city])->value('name');
                // if ( $city ) {
                //     $region_address = $region_address.$city;
                //     $district = db('region')->where(['id'=>$row->district])->value('name');
                //     if ( $district ) {
                //         $region_address = $region_address.$district;
                //     }
                // }
                // $row->region_address = $region_address?$region_address:'';
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 查看
     */
    public function staff_volunteers($ids = null)
    {
        $this->assignconfig("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf                                   = ['volunteer.staff_id' => $ids];
            $list                                        = $this->model
                ->with(['user', 'volunteerspecialty'])
                ->where($where)
                ->where($where_buf)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
                $region_address = db('region')->where(['id' => $row->province])->value('name');
                $city           = db('region')->where(['id' => $row->city])->value('name');
                if ($city) {
                    $region_address = $region_address . $city;
                    $district       = db('region')->where(['id' => $row->district])->value('name');
                    if ($district) {
                        $region_address = $region_address . $district;
                    }
                }
                $row->region_address = $region_address ? $region_address : '';
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

    public function volunteer_list_no($ids)
    {
        $this->assignconfig("ids", $ids);
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {

            $list = Db::name('activity_sign')->alias('s')
                ->join('activity a', 'a.id=s.activity_id')
                ->join('volunteer v', 'v.id=s.vo_id')
                ->join('area area', 'area.id=s.center_id')
                ->field('v.name,s.vo_id as id')
                ->where(['s.activity_id' => $ids])
                ->where('s.sign_time', '=', 0)

                ->order('s.id desc')
                ->paginate(100);

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }
    /**
     * 新增
     */
    public function add($ids = null)
    {

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (! in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params             = $this->preExcludeFields($params);
                $result             = false;
                $params['province'] = input('province', 0);
                $params['city']     = input('city', 0);
                $params['district'] = input('district', 0);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $Volunteer = Db::name('volunteer')->where('user_id', $params['user_id'])
                        ->where('affiliated_center_id', $params['affiliated_center_id'])->find();
                    if ($Volunteer) {
                        $this->error(__('該中心已存在此義工'));
                    }
                    $result = $this->model->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }

        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (! $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            $pk       = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                    db('volunteer_audit')->where(['id' => $v->volunteer_audit_id])->update(['deletetime' => time()]);
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (! $row) {
            $this->error(__('No Results were found'));
        }
        $user            = db('user')->where(['id' => $row['user_id']])->find();
        $row['avatar']   = $user['avatar'];
        $row['nickname'] = $user['nickname'];
        $province        = db('region')->field('id as value, name')->where(['id' => $row['province']])->find();
        $city            = db('region')->field('id as value, name')->where(['id' => $row['city']])->find();
        $district        = db('region')->field('id as value, name')->where(['id' => $row['district']])->find();
        $this->view->assign("province", $province);
        $this->view->assign("city", $city);
        $this->view->assign("district", $district);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (! in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params             = $this->preExcludeFields($params);
                $result             = false;
                $params['province'] = input('province', 0);
                $params['city']     = input('city', 0);
                $params['district'] = input('district', 0);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 互助廣場指派義工
     */
    public function indexsss($ids = 0)
    {
        $task    = db('help_task')->where(['id' => $ids])->find();
        $user_id = $task['user_id'];
        $this->assignconfig("ids", $ids);
        $this->view->assign("ids", $ids);

        if ($this->request->isPost()) {
            $volunteer_id_post = input('post.volunteer_id');
            if ($volunteer_id_post) {
                $result = false;
                Db::startTrans();
                try {
                    $save                     = [];
                    $save['volunteer_id']     = $volunteer_id_post;
                    $save['distributiontime'] = time();
                    $save['status']           = '4';
                    $result                   = db('help_task')->where(['id' => $ids])->update($save);
                    // 通知用戶
                    sendMessage(1, '您的求助訂單' . $task['task_no'] . '已被接單', '', $task['user_id'], 2, $task['id']);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success('指派成功');
                } else {
                    $this->error(__('No rows were updated'));
                }
            }

            $this->success('操作成功');
        }
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_buf                                   = ['user.id' => ['neq', $user_id]];
            $list                                        = $this->model
                ->with(['user', 'volunteerspecialty'])
                ->where($where)
                ->where($where_buf)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);
                $row->getRelation('volunteerspecialty')->visible(['name']);
            }

            $result = ["total" => $list->total(), "rows" => $list->items()];

            return json($result);
        }
        return $this->view->fetch();
    }

}
